package com.jingdianjichi.oss.util;

import com.jingdianjichi.oss.entity.FileInfo;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * MinioUtil 类
 *
 * @author 熊苏鹏1
 * @date 2025/2/27 20:19
 * @description minio工具类
 */
@Component
public class MinioUtil {
    @Resource
    private MinioClient minioClient;
    /**
     * 创键Bucket桶
     */
    public void createBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //判断是否存在
        boolean exist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!exist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

    }
    /**
     * 上传文件到MinIO服务器
     *
     * @param inputStream 文件输入流，用于读取文件内容
     * @param bucketName 存储桶名称，指定文件要上传到的存储桶
     * @param objectName 文件对象名称，即文件在存储桶中的路径和名称
     * @throws ServerException 如果服务器发生错误，则抛出此异常
     * @throws InsufficientDataException 如果提供的数据不足以完成操作，则抛出此异常
     * @throws ErrorResponseException 如果接收到的响应错误，则抛出此异常
     * @throws IOException 如果发生I/O错误，则抛出此异常
     * @throws NoSuchAlgorithmException 如果无法找到所需的哈希算法，则抛出此异常
     * @throws InvalidKeyException 如果提供的密钥无效，则抛出此异常
     * @throws InvalidResponseException 如果接收到的响应无效，则抛出此异常
     * @throws XmlParserException 如果XML解析失败，则抛出此异常
     * @throws InternalException 如果发生内部错误，则抛出此异常
     */
    public void uploadFile(InputStream inputStream, String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 使用MinIO客户端的putObject方法上传文件
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(inputStream,-1,Integer.MAX_VALUE).build());
    }
    /**
     * 列出所有桶
     */
    public List<String> geAllBucket() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        return minioClient.listBuckets().stream().map(Bucket::name).collect(Collectors.toList());

    }
    /**
     * 列出当前桶及所有文件
     */
    public List<FileInfo> getAllFile(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        List<FileInfo> fileInfos  = new ArrayList<>();
        for (Result<Item> result : results) {
            FileInfo fileInfo = new FileInfo();
            Item item =  result.get();
            fileInfo.setFileName(item.objectName());
            fileInfo.setDirectoryFlag(item.isDir());
            fileInfo.setEtag(item.etag());
            fileInfos.add(fileInfo);
        }
        return fileInfos;
    }
    /**
     * 下载文件
     */
    public InputStream downloadFile(String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }
    /**
     * 删除文件
     */
    public void deleteFile(String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }
    /**
     * 删除桶
     */
    public void deleteBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
    }
    /**
     * 获取文件预览URL
     *
     * @param bucketName 存储桶名称
     * @param objectName 对象名称
     * @return 返回文件的预览URL
     * @throws Exception 如果获取URL过程中发生错误，则抛出异常
     */
    public String getPreviewFileUrl(String bucketName, String objectName) throws Exception{
        // 构建获取预签名对象URL的参数
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET) // 使用GET方法
                .bucket(bucketName) // 指定存储桶名称
                .object(objectName) // 指定对象名称
                .build();
        // 调用MinIO客户端方法获取预签名对象URL并返回
        return minioClient.getPresignedObjectUrl(args);
    }


}
